﻿using System;
using System.IO;
using System.Security.Principal;
using System.Windows;
using Microsoft.Win32;

namespace ServeAnything
{
    public partial class MainWindow : Window
    {
        private readonly ViewModel _viewModel = new ViewModel(); 

        public MainWindow()
        {
            InitializeComponent();
            DataContext = _viewModel;

            /* Default username */
            var identity = WindowsIdentity.GetCurrent();
            if (identity != null)
                _viewModel.Username = identity.Name;
        }

        private async void installButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _viewModel.Status = "Installing...";
                var username = _viewModel.RunAsSystem ? null : _viewModel.Username;
                var password = _viewModel.RunAsSystem ? null : _viewModel.Password;
                await ServiceDelegateInstaller.InstallAsync(_viewModel.ServiceName, _viewModel.Path, _viewModel.Arguments, username, password);
                _viewModel.Status = "Installed";
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("Can't access service control.  Make sure you're running as admin.");
                _viewModel.Status = "Failed";
            }
            catch(Exception)
            {
                _viewModel.Status = "Failed";
            }
        }

        private void OpenButton_OnClick(object sender, RoutedEventArgs e)
        {
            var dialog = new OpenFileDialog();
            dialog.Filter = "Executables|*.exe|All Files|*.*";

            if (dialog.ShowDialog().Value)
            {
                _viewModel.Path = dialog.FileName;

                if (string.IsNullOrEmpty(_viewModel.ServiceName))
                {
                    _viewModel.ServiceName = Path.GetFileNameWithoutExtension(dialog.SafeFileName);
                    _viewModel.ServiceName = ToUppercase(_viewModel.ServiceName);
                }
            }
        }

        private async void UninstallButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _viewModel.Status = "Uninstalling...";
                await ServiceDelegateInstaller.UninstallAsync(_viewModel.ServiceName);
                _viewModel.Status = "Uninstalled";
            }
            catch (Exception)
            {
                _viewModel.Status = "Failed";
            }
        }

        private static string ToUppercase(string s)
        {
            // Check for empty string.
            if (string.IsNullOrEmpty(s))
            {
                return string.Empty;
            }
            // Return char and concat substring.
            return char.ToUpper(s[0]) + s.Substring(1);
        }
    }
}
